# -*- coding: utf-8 -*-
"""
summary:
    博客 views
license:
    GNU General Public License v3 <http://www.gnu.org/licenses/gpl.html>
authors:
    Jason Lee <huacnlee@gmail.com>
"""

import traceback
from django.http import HttpResponse,Http404, HttpResponseRedirect, HttpResponseServerError
from django.template import Context, loader
from django.shortcuts import get_object_or_404
from django.core.paginator import Paginator
from django.db.models import Q
from django.core import serializers
from settings import *
from apps.models import User,Language
from apps.blog.models import Profile,Post
from utils import formatter,function,mailer,uploader,logs
from utils.components import ExecuteState
from utils.dict import errorinfos
from utils.helper import view,convert

def home(request,page_index=1,template='home.html'):
    """
    summary:
        首页
    author:
        李华顺<huacnlee@gmail.com>
    """
    posts = []
    pagebar = ''
    try:
        posts = Post.objects.filter(
                                    status=1,
                                    digg_count__gte = POST_HOME_SHOW_LEAST_DIGG_COUNT,
                                    allow_show_in_home = True
                                    ).order_by("-id")
        paginator = Paginator(posts,GLOBAL_PAGE_SIZE)
        pagebar = formatter.pagebar(paginator,page_index,GLOBAL_PAGE_SIZE)
        posts = paginator.page(page_index).object_list
    except:
        logs.write(traceback)

    data = {
            'current_profile' : request.current_profile,
            'pagebar' : pagebar,
            'posts' : posts,
            }

    return view.out_page(template,data)

def blogs(request,template='blogs.html'):
    """
    summary:
        博客列表
    author:
        李华顺<huacnlee@gmail.com>
    """
    profiles = Profile.objects.all().order_by('-user__score')
    data = {
            'current_profile' : request.current_profile,
            'profiles' : profiles,
            }

    return view.out_page(template,data)

def signup(request,template='signup.html'):
    """
    summary:
        注册用户视图
    author:
        李华顺<huacnlee@gmail.com>
    """


    data = {
            'current_profile' : request.current_profile,
            }

    state = ExecuteState()
    if request.POST:
        return _signup_post(request)
    else:
        return view.out_page(template,data)

def _signup_post(request):
    """
    summary:
        注冊Ajax提交
    author:
        李华顺<huacnlee@gmail.com>
    """
    state = ExecuteState()
    realname = view.get_form_val(request,"realname")
    email = view.get_form_val(request,"email")
    about = view.get_form_val(request,"about")


    try:
        # 提交数据库
        user = User(
                     email = email,
                     realname = realname,
                     signup_memo = about,
                     )
        # 验证输入
        state = user.check()

        if not state.success:
            return view.out_text(state.str())

        user.save_simple()

        # 发送Email提醒


        state.message = "申请提交成功。"
        state.success = True
    except:
        logs.write(traceback)
        state.message = "%s" % (errorinfos.unknow)
        state.success = False

    return view.out_text(state.str())

def signup_active(request,template="signup_active.html"):
    """
    summary:
        注册激活页面
    author:
        李华顺 <huacnlee@gmail.com>
    """


    state = ExecuteState()

    # 提交拦截
    if request.POST:
        return _signup_active_post(request)

    key = view.get_query_val(request,"key")

    if key == '':
        return view.out_404()

    # 取要激活的用户的信息
    try:
        user = User.objects.get(active_key = key)
    except (User.DoesNotExist):
        state.message = "激活码有误，无法开通。"
        state.success = False
        return view.out_message(state)
    except:
        logs.write(traceback)
        return view.out_unkonw_error()

    # 取出语言列表
    try:
        languages = Language.objects.all()
    except:
        logs.write(traceback)
        return view.out_unkonw_error()

    result = {
              "active_user" : user,
              "languages" : languages,
              }

    return view.out_page(template,result)

def _signup_active_post(request):
    """
    summary:
        激活博客，Ajax提交
    author:
        李华顺 <huacnlee@gmail.com>
    """
    state = ExecuteState()

    key = view.get_form_val(request,'key')
    password = view.get_form_val(request,'password')
    title = view.get_form_val(request,'title')
    slug = view.get_form_val(request,'slug')

    try:
        user = User.objects.get(active_key = key)

        user.password = password
        user.status = 1
        user.active_key = ""
        user.save(modify_pwd = True)

        profile = Profile(
                          user = user,
                          title = title,
                          slug = slug,
                          )
        state = profile.check()
        if state.success:
            profile.save()

            # 发送激活成功的Email

            state.message = "激活成功。"
            state.success = True

    except (User.DoesNotExist):
        state.message = "激活码有误，无法开通。"
        state.success = False
    except:
        logs.write(traceback)
        state.message = "%s" % (errorinfos.unknow)
        state.success = False

    return view.out_text(state.str())


def signin(request,template='signin.html'):
    """
    summary:
        登陆页面
    author:
        李华顺<huacnlee@gmail.com>
    """


    state = ExecuteState()
    email = ""

    if request.POST:
        email = view.get_form_val(request,"email")
        password = view.get_form_val(request,"password")

        try:
            user = User.objects.get(email = email,password = function.md5_encode(password))

            # 保存session信息
            view.login_save(request,user)

            return HttpResponseRedirect(request.referer_url)

        except (User.DoesNotExist):
            state.message = "用户名或密码错误，请重新输入。"
            state.success = False
        except:
            logs.write(traceback)
            return view.out_unknow_error()
    else:
        if view.is_logined(request):
            return HttpResponseRedirect(request.referer_url)
        state.message = ""

    data = {
            "state" : state,
            "email" : email,
            'current_profile' : request.current_profile,
            }

    return view.out_page(template,data)

def signout(request):
    """
    summary:
        登出
    author:
        李华顺<huacnlee@gmail.com>
    """


    view.login_out(request)
    return HttpResponseRedirect(request.referer_url)
